<template>
  <div>
    <a-table
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :rowKey="(record, index) => record.id"
      :data-source="tableData"
      bordered
    >
      <template
        v-for="col in ['travelTitle', 'travelAuthor']"
        #[col]="{ text, record }"
        :key="col"
      >
        <div>
          <a-input
            v-if="editableData[record.key]"
            v-model:value="editableData[record.key][col]"
            style="margin: -5px 0"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template #operation="{ record }">
        <div class="editable-row-operations">
          <span v-if="editableData[record.key]">
            <a @click="save(record.key)">Save</a>
            <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.key)">
              <a>Cancel</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="edit(record.key)">Edit</a>
          </span>
        </div>
      </template>
      <template #title>
        <a-button type="primary" class="distance" @click="showModal">
          <PlusSquareOutlined />
          添加
        </a-button>
        <a-button
          type="danger"
          class="distance"
          :disabled="!hasSelected"
          :loading="loading"
          @click="start"
        >
          <DeleteOutlined />
          批量删除
        </a-button>
        搜索：
        <a-input-search
          v-model:value="search"
          placeholder="input search text"
          enter-button
        />
      </template>
    </a-table>
    <a-modal
      title="Title"
      v-model:visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item ref="account" label="Activity account" name="account">
          <a-input v-model:value="formState.account" />
        </a-form-item>
        <a-form-item ref="name" label="Activity name" name="name">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="Activity time" required name="date1">
          <a-date-picker
            v-model:value="formState.date1"
            show-time
            type="date"
            placeholder="Pick a date"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
  import { cloneDeep } from 'lodash-es'
  import { computed, reactive, ref, toRefs } from 'vue'
  import { getTravel } from '../../api/httpapi.js'
  import { PlusSquareOutlined, DeleteOutlined } from '@ant-design/icons-vue'
  //   const data = () => {
  //     const datas = []
  //     getTravel().then(function (res) {
  //       datas = res.data
  //     })
  //     return datas
  //   }

  //   for (let i = 0; i < 100; i++) {
  //     data.push({
  //       key: i.toString(),
  //       name: `Edrward ${i}`,
  //       age: 32,
  //       address: `London Park no. ${i}`,
  //     })
  //   }

  export default {
    components: {
      PlusSquareOutlined,
      DeleteOutlined,
    },
    setup() {
      const columns = [
        {
          title: 'Title',
          dataIndex: 'travelTitle',
          width: '25%',
          slots: {
            customRender: 'travelTitle',
          },
        },
        {
          title: 'Author',
          dataIndex: 'travelAuthor',
          width: '15%',
          slots: {
            customRender: 'travelAuthor',
          },
        },
        // {
        //   title: 'address',
        //   dataIndex: 'address',
        //   width: '40%',
        //   slots: {
        //     customRender: 'address',
        //   },
        // },
        {
          title: 'operation',
          dataIndex: 'operation',
          slots: {
            customRender: 'operation',
          },
        },
      ]
      let data = []
      let dataSource = ref(data)
      let dataAll = ref(data)
      const editableData = reactive({})
      getTravel().then(function (res) {
        dataSource.value = res.data
        dataAll.value = res.data
      })
      let search = ref('')
      const tableData = computed(() => {
        if (search.value) {
          return dataAll.value.filter((data) => {
            return Object.keys(data).some((key) => {
              return String(data[key]).toLowerCase().indexOf(search.value) > -1
            })
          })
        }
        return dataAll.value
      })
      const edit = (key) => {
        editableData[key] = cloneDeep(
          dataSource.value.filter((item) => key === item.key)[0]
        )
      }

      const save = (key) => {
        Object.assign(
          dataSource.value.filter((item) => key === item.key)[0],
          editableData[key]
        )
        delete editableData[key]
      }

      const cancel = (key) => {
        delete editableData[key]
      }
      const state = reactive({
        selectedRowKeys: [],
        // Check here to configure the default column
        loading: false,
      })
      const hasSelected = computed(() => state.selectedRowKeys.length > 0)

      const start = () => {
        console.log('得到: ', state.selectedRowKeys)
        state.loading = true // ajax request after empty completing

        setTimeout(() => {
          state.loading = false
          state.selectedRowKeys = []
        }, 1000)
      }

      const onSelectChange = (selectedRowKeys) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        state.selectedRowKeys = selectedRowKeys
      }
      const modalText = ref('Content of the modal')
      const visible = ref(false)
      const confirmLoading = ref(false)

      const showModal = () => {
        visible.value = true
      }

      const handleOk = () => {
        modalText.value = 'The modal will be closed after two seconds'
        confirmLoading.value = true
        setTimeout(() => {
          visible.value = false
          confirmLoading.value = false
        }, 2000)
      }
      const formState = reactive({
        account: '',
        name: '',
        date1: undefined,
      })
      const rules = {
        name: [
          {
            required: true,
            message: 'Please input Activity name',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 5,
            message: 'Length should be 3 to 5',
            trigger: 'blur',
          },
        ],
        account: [
          {
            required: true,
            message: 'Please input Activity name',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 5,
            message: 'Length should be 3 to 5',
            trigger: 'blur',
          },
        ],
        date1: [
          {
            required: true,
            message: 'Please pick a date',
            trigger: 'change',
            type: 'object',
          },
        ],
      }
      const formRef = ref()
      const resetForm = () => {
        formRef.value.resetFields()
      }

      return {
        dataSource,
        columns,
        editingKey: '',
        editableData,
        edit,
        save,
        cancel,
        tableData,
        search,
        hasSelected,
        ...toRefs(state),
        // func
        start,
        onSelectChange,
        modalText,
        visible,
        confirmLoading,
        showModal,
        handleOk,
        formState,
        resetForm,
        rules,
      }
    },
  }
</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
  .distance {
    margin-right: 20px;
  }
</style>
